//
//  STEmojiKeyboard.m
//  STEmojiKeyboard
//
//  Created by zhenlintie on 15/5/29.
//  Copyright (c) 2015年 sTeven. All rights reserved.
//

#import "STEmojiKeyboard.h"

#import "EmojiTextAttachment.h"

#import "FaceModel.h"

#define kSTEmojiKeyboardFrame CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), 240)
#define kSTEmojiToolBarHeight 40

#define kSTEmojiFaceScrollHeight 175

@interface STEmojiToolBar : UIView
@property (strong, nonatomic) void (^deleteHandler)();
@end

@implementation STEmojiToolBar{
    BOOL _beginDelete;
    CGFloat _time;
}

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:CGRectMake(0, CGRectGetHeight(kSTEmojiKeyboardFrame)-kSTEmojiToolBarHeight, CGRectGetWidth(kSTEmojiKeyboardFrame), kSTEmojiToolBarHeight)]){
        _beginDelete = NO;
          [self loadUI];
    }
    return self;
}

- (void)loadUI{
    
    CGFloat w = CGRectGetWidth(self.frame)/6;
    CGFloat h = CGRectGetHeight(self.frame);
    CGFloat left = [UIScreen mainScreen].bounds.size.width-w-5;
    
    UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteButton.frame = CGRectMake(left, 0, w, h);
    deleteButton.tag = 100;

    [deleteButton setImage:[[UIImage imageNamed:@"emotion_delete_highlighted"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]  forState:UIControlStateNormal];
    [deleteButton addTarget:self action:@selector(deleteButtonTouchDown) forControlEvents:UIControlEventTouchDown];
    [deleteButton addTarget:self action:@selector(deleteCancel) forControlEvents:UIControlEventTouchUpInside];
    [deleteButton addTarget:self action:@selector(deleteCancel) forControlEvents:UIControlEventTouchDragOutside];
    [self addSubview:deleteButton];
}

- (void)deleteButtonTouchDown{
    if (self.deleteHandler){
        self.deleteHandler();
        _beginDelete = YES;
        _time = 0.3;
        [self deleteDown];
    }
}

- (void)deleteCancel{
    _beginDelete = NO;
}

- (void)deleteDown{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (_beginDelete){
            if (self.deleteHandler){
                self.deleteHandler();
            }
            _time = 0.1;
            [self deleteDown];
        }
    });
}

@end

@interface STEmojiKeyboard ()<UIScrollViewDelegate>

@property (strong, nonatomic) STEmojiToolBar *toolBar;
@property (nonatomic,strong) UIScrollView *faceScrollView;
@property (nonatomic,strong) NSArray *faceAry;
@property (nonatomic,strong) UIPageControl *page;

@end

@implementation STEmojiKeyboard

+ (instancetype)keyboard{
    static dispatch_once_t onceToken;
    static STEmojiKeyboard *_sharedKeyboard;
    dispatch_once(&onceToken, ^{
        _sharedKeyboard = [self new];
    });
    return _sharedKeyboard;
}

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:kSTEmojiKeyboardFrame]){
        self.clipsToBounds = NO;
        self.backgroundColor = [UIColor whiteColor];
        [self loadUI];

    }
    return self;
}

- (BOOL)enableInputClicksWhenVisible{
    return YES;
}

- (void)loadUI{

    /**
     *  工具条  X号
     */
     _toolBar = [ STEmojiToolBar new];
    _toolBar.backgroundColor = [UIColor colorWithRed:(244)/255.0 green:(244)/255.0 blue:(244)/255.0 alpha:1];
    __weak typeof(self) ws = self;

    [_toolBar setDeleteHandler:^{
        [ws deletePressed];
    }];

    [self addSubview:_toolBar];
    
    
    /**
     *  表情 ScrollView
     */
    CGFloat ScrollWidth = [UIScreen mainScreen].bounds.size.width;
    
    _faceScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, ScrollWidth, kSTEmojiFaceScrollHeight)];
    
    _faceScrollView.pagingEnabled = YES;
    _faceScrollView.bounces = NO;
    _faceScrollView.showsHorizontalScrollIndicator = NO;
    _faceScrollView.showsVerticalScrollIndicator = NO;
    _faceScrollView.delegate = self;
//    _faceScrollView.backgroundColor = [UIColor whiteColor];
    [self addSubview:_faceScrollView];
    
    self.faceAry = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"Face" ofType:@".plist"]];
    
    NSInteger count = self.faceAry.count/24;
    
    if (self.faceAry.count%24>0) {
        count += 1;
    }
    
    _faceScrollView.contentSize = CGSizeMake(ScrollWidth*count, 10);
    
    for (int i = 0; i < count; i++) {
        UIView * v = [[UIView alloc] initWithFrame:CGRectMake(ScrollWidth*i, 0, ScrollWidth, kSTEmojiFaceScrollHeight)];
        [_faceScrollView addSubview:v];
     
        for (int j = 0; j < 3; j++) {
            
            for (int k = 0; k < 8; k++) {
                UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
                
                int temp = 24*i+8*j+k;

                if (temp<self.faceAry.count) {
                    
                    FaceModel *model = [[FaceModel alloc]initWithDictionary:self.faceAry[temp] error:nil];
                    
                    btn.tag = 100+temp;
                    
                    // 格式化输出 001 -> %03d
                    [btn setImage:[UIImage imageNamed:model.png] forState:UIControlStateNormal];
                    
                    
                    CGFloat ww = (ScrollWidth-10*9)/8;
                    CGFloat xx = 10+(10+ww)*k;
                    
                    CGFloat hh = 20+(20+(_faceScrollView.frame.size.height-20*4)/3)*j;
                    btn.frame = CGRectMake(xx, hh, ww, ww);
                    
                    
                    [btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
                    [v addSubview:btn];

                }
            
               
            }
        }
    }
    
    
    
    _page = [[UIPageControl alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/4, H(_faceScrollView)+5, SCREEN_WIDTH/2, 15)];
    _page.numberOfPages = count;
    _page.pageIndicatorTintColor = [UIColor lightGrayColor];;
    _page.currentPageIndicatorTintColor = linColor;
    _page.currentPage = _faceScrollView.contentOffset.x/SCREEN_WIDTH;
    [self addSubview:_page];


}

- (void)click:(UIButton *)btn{
    
    FaceModel *model = [[FaceModel alloc]initWithDictionary:self.faceAry[btn.tag-100] error:nil];

    [self.deleget FaceClickWhithImageName:model.png emojiText:model.text];
}

- (void)changeKeyboard{
    [(UIControl *)self.textView resignFirstResponder];
    [(UITextView *)self.textView setInputView:nil];
    [(UIControl *)self.textView becomeFirstResponder];
}

- (void)deletePressed{
    [self.textView deleteBackward];
    [[UIDevice currentDevice] playInputClick];
    [self textChanged];
}

- (void)insertEmoji:(NSString *)emoji{
    [[UIDevice currentDevice] playInputClick];
    [self.textView insertText:emoji];
    [self textChanged];
}

- (void)textChanged{
    if ([self.textView isKindOfClass:[UITextView class]])
        [[NSNotificationCenter defaultCenter] postNotificationName:UITextViewTextDidChangeNotification object:self.textView];
    else if ([self.textView isKindOfClass:[UITextField class]])
        [[NSNotificationCenter defaultCenter] postNotificationName:UITextFieldTextDidChangeNotification object:self.textView];
}

#pragma mark - setter
- (void)setTextView:(id<UITextInput>)textView{
    if ([textView isKindOfClass:[UITextView class]]) {
        [(UITextView *)textView setInputView:self];
    }
    else if ([textView isKindOfClass:[UITextField class]]) {
        [(UITextField *)textView setInputView:self];
    }
    _textView = textView;
}


-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
_page.currentPage = scrollView.contentOffset.x/SCREEN_WIDTH;

}


@end

